<?php

namespace app\api\controller;

use app\admin\model\agent\Agent;
use app\admin\model\order\Spelldetail;
use app\common\controller\Api;
use think\Config;
use think\Db;
use think\Exception;

/**
 * 会员信息接口
 */
class Mc extends Api
{
    protected $noNeedLogin = ['kfInfo'];
    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 个人中心
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function userInfo()
    {
        if(empty($this->auth->getUser())){
            $data = array(
                "nickname" => "",
                "avatar" => "",
                "mobile" => "",
                "money" => "0.00",
                "referee" => 0,
                "refereeMobile" => '0' ,
                "agent" => \app\common\model\User::getAgentInfo(0),
                "inviteCode"=>"",
            );
        }else {
            $mobile = $this->auth->mobile;
            $refereeMobile= \app\admin\model\User::where(['id'=>$this->auth->referee])->value('mobile');
            $data = array(
                "nickname" => $this->auth->nickname,
                "avatar" => $this->auth->avatar,
                "mobile" => !empty($mobile) ? $mobile: "",
                "money" => $this->auth->money,
                "referee" => $this->auth->referee,
                "refereeMobile" =>substr($refereeMobile, 0,3)."****".substr($refereeMobile, 7,4),
                "agent" => \app\common\model\User::getAgentInfo($this->auth->agent),
                "inviteCode"=>$this->auth->invite_code,
            );
        }
        $this->success("个人中心",$data);
    }
    /**
     * 设置信息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function setting()
    {
        $upInfo = [];
        $referee = $this->auth->referee;
        if(!empty($referee)){
            $upInfo = \app\common\model\User::where('id',$referee)->field('id,mobile')->find();
            if(empty($upInfo)){
                $upInfo['nickname']='';
            }else{
                $upInfo['nickname']=substr($upInfo['mobile'], 0,3)."****".substr($upInfo['mobile'], 7,4);
            }
        }
        $data = array(
            "upInfo"=>$upInfo,
            "referee"=>$referee,
            "mobile"=>$this->auth->mobile,
            "isauth"=>$this->auth->isauth,
        );
        $this->success("设置信息",$data);
    }
    /**
     * 修改手机号
     * @ApiMethod   (POST)
     * @param string mobile  手机号
     * @param string code  验证码
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function updateMobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request("mobile");
        if(empty($mobile)){
            $this->error("请输入手机号");
        }
        $users = \app\admin\model\User::where('mobile',$mobile)->find();
        if(!empty($users)){
            $this->error("当前手机号已存在");
        }
        $code = $this->request->request('code');
        if(empty($code)){
            $this->error("请输入验证码");
        }
        $ret = \app\common\library\Sms::check($mobile, $code, 'update');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $user->mobile = $mobile;
        $user->save();
        $this->success("信息修改成功");
    }
    /**
     * 图片上传
     * @ApiMethod   (POST)
     * @param string thumb  图片（base64）
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn(
    {
    "code": 1,
    "msg": "图片上传成功",
    "time": "1575621702",
    "data": {
    "thumb": "http://fastadmin.www.com/uploads/20191206/20191206164142_53806.png"
    }
    }
    )
     */
    public function upload()
    {
        $thumb = $this->request->request("thumb/s");
        if(empty($thumb)){
            $this->error(__('Failed to get picture information'));
        }
        $user = $this->auth->getUser();
        $thumb = \fast\Utils::base64pic($thumb,$user->id);
        if($thumb == false){
            $this->error(__('Image upload failed'));
        }
        $data = [
            "thumb"=>$thumb
        ];
        $this->success(__('Picture uploaded successfully'),$data);
    }
    /**
     * 意见反馈
     * @ApiMethod   (POST)
     * @ApiParams(name="title", type="string", required=true, description="类型")
     * @ApiParams(name="info", type="string", required=true, description="意见")
     * @ApiParams(name="thumbs", type="array", required=false, description="图片")
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn(
    {
    "code": 1,
    "msg": "谢谢您的意见，我们会继续努力的！",
    "time": "1575624606",
    "data": null
    }
    )
     */
    public function feedback()
    {
        $title = $this->request->request("title/s");
        $info = $this->request->request("info/s");
        $thumbs = $this->request->request("thumbs/a");
        if(empty($title) || empty($info)){
            $this->error(__('Please leave your valuable comments'));
        }
        $user = $this->auth->getUser();
        $model = new \app\admin\model\article\Idea();
        $isback = $model->where('uid',$user->id)->where('createtime','>=',time()-300)->find();
        if(!empty($isback)){
            $this->error(__('Do not operate frequently'));
        }
        $model::create([
            "uid"=>$user->id,
            "title"=>$title,
            "info"=>$info,
            "thumbs" =>!empty($thumbs)?implode(",",$thumbs):null,
            "status"=>'normal',
            "createtime"=>time(),
            "updatetime"=>time(),
        ]);
        $this->success(__('Thank you for your comments, we will continue to work hard!'));
    }
    /**
     * 海报信息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function poster()
    {
        $data = $this->redis->get($this->cacheKey);
        if(!empty($data)){
            $this->success(__("Poster information return!"),json_decode($data,true));
        }
        $user = $this->auth->getUser();
        $shareThumbs = \think\config::get('site.shareappthumbs');
        if(empty($shareThumbs)){
            $this->error(__('Poster configuration missing'));
        }
        $qrcodeUrl = $this->auth->getUserUrl();
        foreach ($shareThumbs as $k=>$v){
            $data = [
                "uid"=>$user->id,
                "tpl"=>$v,
                "qrcode_url"=>$qrcodeUrl,
            ];
            $qrcode = new \app\common\library\Poster($data);
            $url = $qrcode->run();
            $thumbs[] = [
                "thumb"=>$url,
            ];
        }
        $data = [
            "info"=>"123",
            "thumbs"=>$thumbs,
            "url"=>$qrcodeUrl,
            "inviteCode"=>$user->invite_code,
        ];
        $this->redis->set($this->cacheKey,json_encode($data),6000);
        $this->success(__("Poster information return!"),$data);
    }
    /**
     * 关于我们
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function aboutUs()
    {
        $data = array(
            "name"=>\fast\Utils::toMedia(\think\config::get('site.name')),
            "logo"=>\fast\Utils::toMedia(\think\config::get('site.sitelogo')),
            "qrcode"=>request()->domain()."/api/auth/qrcode?code=".base64_encode($this->auth->getUserUrl()),
            "banquan1"=>'Copyright@2008-'.date("Y",time()),
            "banquan2"=>\think\config::get("site.beian"),
        );
        $this->success("关于我们",$data);
    }
    /**
     * 绑定上级
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="inviteCode", type="string", required=true, description="邀请码")
     */
    public function bindUser()
    {
        $user = $this->auth->getUser();
        if($user->referee>0){
            $this->success("已绑定上级");
        }
        $invite_code = $this->request->request("inviteCode");
        if(empty($invite_code)){
           $this->error("请填写邀请码");
        }
        Db::startTrans();
        try{
            \app\common\model\Relation::updateUserRelation($user,$invite_code);
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success("绑定成功");
    }
    /**
     * 实名认证
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="username", type="string", required=true, description="姓名")
     * @ApiParams(name="idcard", type="string", required=true, description="身份证号")
     */
    public function auth()
    {
        $model = new \app\admin\model\user\Auth();
        $info = $model->where("uid",$this->auth->id)->find();
        if($this->auth->isauth == 1){
            $this->success("实名认证成功",['data'=>$info]);
        }
        $username = $this->request->request("username");
        $idcard = $this->request->request("idcard");
        if(empty($username) || empty($idcard)){
            $this->error("请填写实名信息");
        }
        $idcardInfo = $model->where("idcard",$idcard)->where('uid','<>',$this->auth->id)->find();
        if(!empty($idcardInfo)){
            $this->error("身份证号已实名验证");
        }
        if(!empty($info)){
            $info->save(["username"=>$username,'idcard'=>$idcard,'status'=>1,"updatetime"=>time()]);
        }else {
            $model->insert(array(
                "uid" => $this->auth->id,
                "username" => $username,
                "idcard" => $idcard,
                "status" => 1,
                "createtime" => time(),
                "updatetime" => time()
            ));
        }
        try{
            $aop = new \app\common\library\Aop();
            $orderId = \fast\Utils::getOrderId("auth",$this->auth->id);
            $info = $aop->init([
                "orderId"=>$orderId,
                "username"=>$username,
                "idcard"=>$idcard
            ]);
            if($info['code'] != '10000'){
                $this->error("实名认证初始化失败:".$info['msg']);
            }
            $model->where('uid',$this->auth->id)->update(['orderId'=>$orderId,'certify_id'=>$info['certify_id']]);
            $authUrl = $aop->getUrl($info['certify_id']);
        }catch (\Exception $e){
            $this->error("实名认证失败:".$e->getMessage());
        }
        $this->success("实名认证链接",['authUrl'=>$authUrl]);
    }
    /**
     * 实名认证验证接口
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function authFace()
    {
        $model = new \app\admin\model\user\Auth();
        $info = $model->where("uid",$this->auth->id)->find();
        if(empty($info)){
            $this->error("实名信息获取失败");
        }
        if($info['status'] == 2){
            $this->success("实名认证成功",['data'=>$info]);
        }
        try{
            $aop = new \app\common\library\Aop();
            $data = $aop->getInfo($info->certify_id);
            if($data['code'] == '10000' && $data['passed'] == "T") {
                $info->save(['status' => '2', 'info' => '实名认证成功', 'updatetime' => time()]);
                \app\admin\model\User::where('id', $this->auth->id)->update(['isauth' => 1]);
            }else{
                $this->error("实名认证失败:".$data['msg']);
            }
        }catch (\Exception $e){
            $this->error("实名认证失败:".$e->getMessage());
        }
        $this->success("实名认证成功",['data'=>$info]);
    }
    /**
     * 添加账户
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="id", type="string", required=true, description="换绑时传添加为0")
     * @ApiParams(name="type", type="string", required=true, description="类型bank银行卡alipay支付宝")
     * @ApiParams(name="username", type="string", required=true, description="姓名")
     * @ApiParams(name="alipay", type="string", required=true, description="支付宝账户type=alipay时")
     * @ApiParams(name="bankname", type="string", required=true, description="开户行type=bank时")
     * @ApiParams(name="bankbranch", type="string", required=true, description="开户支行type=bank时")
     * @ApiParams(name="bankno", type="string", required=true, description="卡号type=bank时")
     * @ApiParams(name="idcard", type="string", required=true, description="身份证号type=bank时")
     */
    public function addAccount()
    {
        $id = $this->request->request("id",0);
        if(!empty($id)){
            $info = \app\admin\model\user\Account::where('id',$id)->where('uid',$this->auth->id)->where('status',1)->find();
            if(empty($info)){
                $this->error("账户信息获取失败");
            }
        }
        $type = $this->request->request("type","alipay");
        $username = $this->request->request("username","");
        if(empty($username)){
            $this->error("请填写姓名");
        }
        $data = array(
            'uid'=>$this->auth->id,
            "type"=>$type,
            "username"=>$username,
            "status"=>1,
            "createtime"=>time(),
            "updatetime"=>time(),
        );
        if($type == 'alipay'){
            $alipay = $this->request->request("alipay","");
            if(empty($alipay)){
                $this->error("支付宝信息不能为空");
            }
            $data['alipay'] = $alipay;
        }else{
            $bankname = $this->request->request("bankname","");
            if(empty($bankname)){
                $this->error("开户行信息不能为空");
            }
            $bankbranch = $this->request->request("bankbranch","");
            if(empty($bankbranch)){
                $this->error("开户支行信息不能为空");
            }
            $bankno = $this->request->request("bankno","");
            if(empty($bankno)){
                $this->error("银行卡号不能为空");
            }
            $idcard = $this->request->request("idcard","");
            if(empty($idcard)){
                $this->error("身份证号不能为空");
            }
            $data['bankname'] = $bankname;
            $data['bankbranch'] = $bankbranch;
            $data['bankno'] = $bankno;
            $data['idcard'] = $idcard;
        }
        if(!empty($id)){
            \app\admin\model\user\Account::where('id',$id)->update($data);
        }else{
            \app\admin\model\user\Account::insert($data);
        }
        $this->success("添加成功");
    }
    /**
     * 账户记录
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="page", type="string", required=true, description="分页")
     */
    public function accountList()
    {
        $model = new \app\admin\model\user\Account();
        $list = $model->where('uid',$this->auth->id)
            ->where('status','1')
            ->limit(($this->page-1)*$this->limit,$this->limit)
            ->order('id desc')
            ->select();
        $data = [
            "list"=>$list?$list:[],
            "typeList"=>$model->getTypeList(),
            "bankList"=>$model->getBankList(),
            "money"=>$this->auth->money,
            "minPrice"=>\think\config::get("site.withdrawminprice"),
        ];
        $this->success('账户信息返回', $data);
    }
    /**
     * 删除记录
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="id", type="string", required=true, description="删除ID")
     */
    public function delAccount()
    {
        $id = $this->request->request("id",0);
        if(empty($id)){
            $this->error("账户信息获取失败");
        }
        $model = new \app\admin\model\user\Account();
        $info = $model->where('id',$id)->where('uid',$this->auth->id)->where('status',1)->find();
        if(empty($info)){
            $this->error("信息获取失败");
        }
        $info->save(['status'=>9,'updatetime'=>time()]);
        $this->success("删除成功");
    }
    /**
     * 申请提现
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="money", type="string", required=true, description="提现金额")
     * @ApiParams(name="accountId", type="string", required=true, description="账户ID")
     */
    public function withdraw()
    {
        $user = $this->auth->getUser();
        $money = $this->request->request("money",0);
        if(empty($money) || $money<=0 || $money<\think\config::get("site.withdrawminprice")){
            $this->error("提现金额异常");
        }
        if($money>$this->auth->money){
            $this->error("账户不足，无法提现");
        }
        $accountId = $this->request->request("accountId",0);
        if(empty($accountId)){
            $this->error("账户信息获取失败");
        }
        Db::startTrans();
        try{
            \app\admin\model\user\Withdraw::addWithdraw($user,$money,$accountId);
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success("提现申请成功");
    }
    /**
     * 提现记录
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="page", type="string", required=true, description="分页")
     */
    public function withdrawList()
    {
        $model = new \app\admin\model\user\Withdraw();
        $list = $model->where('uid',$this->auth->id)
            ->order('id desc')
            ->limit(($this->page-1)*$this->limit,$this->limit)
            ->field('id,money,type,status,createtime,username,alipay,bankname,bankno,desc')
            ->select();
        $data = [
            "list"=>$list?$list:[],
            "statusInfo"=>$model::getStatusInfo(),
            "typesInfo"=>$model::getTypesInfo()
        ];
        $this->success(__('Withdrawal information return'), $data);
    }
    /**
     * 邀请信息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function inviteInfo()
    {
        $data = array(
            "nums"=>10,
            "price"=>"100",
        );
        $this->success("邀请信息",$data);
    }
    /**
     * 客服信息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function kfInfo()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");

        $data = array(
            "qq"=>\think\config::get("site.qq"),
            "wechat"=>\think\config::get("site.wechat"),
            "mobile"=>\think\config::get("site.mobile"),
            "bdsqurl"=>\think\config::get("site.bdsqurl"),
            "kftime"=>\think\config::get("site.kftime"),
        );
        $this->success("客服信息",$data);
    }
    /**
     * 代理等级
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function agentInfo()
    {
        $model = new \app\admin\model\agent\Agent();
        $list = $model->where('status',1)->order('id asc')
            ->field('id,title,price,thumb,zhi,ping,plevel,agent')
            ->select();
        $model::crontabUp($this->auth->getUser(),$list);
        $data = array(
            "list"=>!empty($list)?$list:[],
            "agent"=>$this->auth->agent,
        );
        $this->success("代理信息获取",$data);
    }
    /**
     * 代理升级
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="agentId", type="string", required=true, description="代理等级")
     */
    public function agentUp()
    {
        $agentId = $this->request->request("agentId",0);
        if(empty($agentId)){
            $this->error("请提交代理等级");
        }
        if($this->auth->agent>=$agentId){
            $this->error("请选择更高等级升级");
        }
        Db::startTrans();
        try{
            $orderId = \app\admin\model\agent\Order::addOrder($this->auth->getUser(),$agentId);
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success("订单创建成功",['orderId'=>$orderId]);
    }
    /**
     * 余额记录
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="page", type="string", required=true, description="分页")
     */
    public function moneyList()
    {
        $model = new \app\admin\model\rebate\Money();
        $query = $model->where('user_id',$this->auth->id);
        $list = $query->order('id desc')
            ->field('id,money,memo,type,createtime,orderId')
            ->limit(($this->page-1)*$this->limit,$this->limit)
            ->select();
        if(!empty($list)){
            foreach ($list as $ks=>&$vs){
                $info = [];
                if(strpos($vs['orderId'],'agent') !== false){
                    $vs['type']=5;
                    $info = \app\admin\model\agent\Order::where('orderId',$vs['orderId'])->field('id,uid,title,agent')->find();
                    $user=\app\admin\model\User::get(['id'=>$info['uid']]);
                    $agent=Agent::get(['id'=>$info['agent']]);
                    $info['thumb']=$agent['thumb'];
                    $info['avatar']=empty($user['avatar'])?\think\config::get('data_conf.default_avatar'):$user['avatar'];
                    $info['mobile']=$user['mobile'];
                }elseif(strpos($vs['orderId'],'pt') !== false){
                    $info = \app\admin\model\SpellOrder::where('orderId',$vs['orderId'])->field('id,goodsName,mobile,thumb,goodsPrice,avatar')->find();
                    if($vs['type']==12){
                        $info = \app\admin\model\order\Spell::where(['orderId'=>$vs['orderId']])->field('id,mobile,avatar,price')->find();
                        if(empty($info)){
                            $vs["info"] = !empty($info)?$info:[];
                            continue;
                        }
                        $goodsInfo=Spelldetail::get(['orderId'=>$vs['orderId']]);
                        $info['goodsPrice']=$info['price'];
                        $info['thumb']=$goodsInfo['image'];
                        $info['goodsName']=$goodsInfo['goodsName'];
                        $info['mobile']=str_replace('****',2865,$info['mobile']);
                    }
                }
                $vs["info"] = !empty($info)?$info:[];
            }
        }
        $data = array(
            "list"=>!empty($list)?$list:[],
            "typeInfo"=>$model->getTypeInfo(),
            "money"=>$this->auth->money,
        );

        $this->success("余额记录信息",$data);
    }
    /**
     * 余额支出记录
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="type", type="string", required=true, description="收益1支付2")
     * @ApiParams(name="page", type="string", required=true, description="分页")
     */
    public function rebateList()
    {
        $model = new \app\admin\model\rebate\Rebate();
        $query = $model->where('uid',$this->auth->id);
        $type = $this->request->request("type",1);
        if($type == 1){
            $query->where('type','in',[6,7,9,12,13]);
        }else{
            $query->where('type',4);
        }
        $list = $query->order('id desc')
            ->field('id,uid,orderId,type,price,createtime')
            ->limit(($this->page-1)*$this->limit,$this->limit)
            ->select();
        if(!empty($list)){
            foreach ($list as $ks=>&$vs){
                $info = [];
                if(strpos($vs['orderId'],'agent') !== false){
                    $vs['type']=5;
                    $info = \app\admin\model\agent\Order::where('orderId',$vs['orderId'])->field('id,uid,title,agent')->find();
                    $user=\app\admin\model\User::get(['id'=>$info['uid']]);
                    $agent=Agent::get(['id'=>$info['agent']]);
                    $info['thumb']=$agent['thumb'];
                    $info['avatar']=empty($user['avatar'])?\think\config::get('data_conf.default_avatar'):$user['avatar'];
                    $info['mobile']=$user['mobile'];
                }elseif(strpos($vs['orderId'],'pt') !== false){
                    $info = \app\admin\model\SpellOrder::where('orderId',$vs['orderId'])->field('id,goodsName,mobile,thumb,goodsPrice,avatar')->find();
                    if($vs['type']==12){
                        $info = \app\admin\model\order\Spell::where('orderId',$vs['orderId'])->field('id,mobile,avatar,price')->find();
                        if(empty($info)){
                            $vs["info"] = !empty($info)?$info:[];
                            continue;
                        }
                        $goodsInfo=Spelldetail::get(['orderId'=>$vs['orderId']]);
                        $info['goodsPrice']=$info['price'];
                        $info['thumb']=$goodsInfo['image'];
                        $info['goodsName']=$goodsInfo['goodsName'];
                        $info['mobile']=str_replace('****',2865,$info['mobile']);
                    }
                }
                $vs["info"] = !empty($info)?$info:[];
            }
        }
        $data = array(
            "list"=>!empty($list)?$list:[],
            "typeInfo"=>$model->getTypeInfo(),
            "money"=>$this->auth->money,
        );
        $this->success("余额记录信息",$data);
    }
}
